// Package handle
//
// 这里是前端API列表
//
// 所有的接口都在这里以及子目录中
package handle

import (
	"server/game/handle/active"
	"server/game/handle/battle"
	"server/game/handle/debug"
	"server/game/handle/getter"
	"server/game/handle/grow"
	"server/game/handle/items"
	"server/game/handle/public"
	"server/game/handle/pvp"
	"server/game/handle/role"
	"server/game/model"
	"server/share/config"
	"time"

	"github.com/hwcer/cosgo"
	"github.com/hwcer/cosgo/values"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
	"github.com/hwcer/yyds/options"
)

/*
所有handle子文件夹必须在这里包含
*/

const (
	AutoSelectCharacter = "AutoSelectCharacter"
)

var (
	_ = items.Register
	_ = active.Register
	_ = battle.Register
	_ = debug.Register
	_ = getter.Register
	_ = grow.Register
	_ = public.Register
	_ = battle.Register
	_ = pvp.Register
	_ = role.Register
)

var db = model.DB()

func init() {
	Register(emit)
	Register(echo)
	Register(ping)
	Register(version)
}

func Register(i interface{}, name ...string) {
	context.Register(i, name...)
}
func echo(c *context.Context) interface{} {
	req := values.Metadata{}
	req[options.ServiceMetadataRequestId] = ""
	c.Send("echo", c.Bytes(), req)
	return true
}

func ping(c *context.Context) interface{} {
	return time.Now().Unix()
}

// version 服务器编译日期
func version(c *context.Context) interface{} {
	return cosgo.Version
}

// emit 上报事件
//
// k int 事件ID  参考全局事件 emitter
// v int 记录数量
func emit(c *context.Context) interface{} {
	k := c.GetInt32("k")
	v := c.GetInt32("v")
	cfg := config.Data.Emitter[k]
	if cfg == nil {
		return errors.ErrConfigEmpty
	} else if cfg.Update == 0 {
		return c.Error("update disabled")
	}
	c.Player.Emit(k, v)
	return true
}
